package com.boy.base;
import com.boy.commonutils.config.MailConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
 * @author whd
 * @date 2024/06/07 16:38:33
 */
@Configuration
public class OurMail {

    @Autowired
    private MailConfig mailConfig;

    @Bean
    JavaMailSenderImpl mailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        this.applyProperties(mailConfig, sender);
        return sender;
    }

    private void applyProperties(MailConfig mailConfig, JavaMailSenderImpl sender) {
        sender.setHost(mailConfig.getHost());
        if (mailConfig.getPort() != null) {
            sender.setPort(mailConfig.getPort());
        }
        sender.setUsername(mailConfig.getUsername());
        sender.setPassword(mailConfig.getPassword());
        sender.setProtocol(mailConfig.getProtocol());
        if (mailConfig.getDefaultEncoding() != null) {
            sender.setDefaultEncoding(mailConfig.getDefaultEncoding().name());
        }

        sender.setJavaMailProperties(this.asProperties());
    }

    private Properties asProperties() {
        Properties properties = new Properties();
        Map<String, String> source = new HashMap<>();
        source.put("mail.smtp.auth", mailConfig.getSmtpAuth());
        source.put("mail.smtp.socketFactory.port", mailConfig.getSocketFactoryPort());
        source.put("mail.smtp.socketFactory.class", mailConfig.getSocketFactoryClass());
        source.put("mail.smtp.socketFactory.fallback", mailConfig.getSocketFactoryFallback());
        source.put("mail.smtp.starttls.enable", mailConfig.getStarttlsEnable());
        source.put("mail.smtp.starttls.required", mailConfig.getStarttlsRequired());
        properties.putAll(source);
        return properties;
    }

}
